//
//  HomeViewController.swift
//  SitPosition
//
//  Created by apple on 2018/12/22.
//  Copyright © 2018 apple. All rights reserved.
//

import UIKit
import Cartography


class HomeViewController: GKNavigationBarViewController {
    
    // MARK: - Subviews
    
    // 背景图
    let backgroundView: UserLoginRegistrationBackground = UserLoginRegistrationBackground()
    
    // 右下角装饰图
    lazy var homepageBookIV: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "homepage_book"))
        iv.contentMode = UIView.ContentMode.scaleAspectFit
        iv.clipsToBounds = true
        return iv
    }()
    
    // 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.Color.primaryLightTextColor
        label.font = Theme.Font.boldFont(ofSize: 26)
        label.numberOfLines = 1
        label.lineBreakMode = .byTruncatingTail
        label.text = Strings.homeTitle
        return label
    }()
    
    lazy var subtitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.Color.primaryLightTextColor
        label.font = Theme.Font.dinotMediumFont(ofSize: 18)
        label.numberOfLines = 1
        label.lineBreakMode = .byTruncatingTail
        label.text = Strings.homeSubtitle
        return label
    }()
    
    // 网格大按钮
    lazy var gridButtons: [HomeGridButton] = {
        let viewStudyBtn = HomeGridButton(
            title: Strings.viewStudy,
            backgroundImage: UIImage(named: "homepage_learning"))
        viewStudyBtn.addTarget(self, action: #selector(_viewStudy), for: UIControl.Event.touchUpInside)
        
        let dataAnalysisBtn = HomeGridButton(
            title: Strings.dataAnalysis,
            backgroundImage: UIImage(named: "homepage_data"))
        dataAnalysisBtn.addTarget(self, action: #selector(_showDataAnalysis), for: UIControl.Event.touchUpInside)
        
        let studySettingsBtn = HomeGridButton(
            title: Strings.studySettings,
            backgroundImage: UIImage(named: "homepage_learning_set"))
        studySettingsBtn.addTarget(self, action: #selector(_showStudySettings), for: UIControl.Event.touchUpInside)
        
        let genericSettingsBtn = HomeGridButton(
            title: Strings.genericSettings,
            backgroundImage: UIImage(named: "homepage_set"))
        genericSettingsBtn.addTarget(self, action: #selector(_showGenericSettings), for: UIControl.Event.touchUpInside)
        
        return [
            viewStudyBtn,
            dataAnalysisBtn,
            studySettingsBtn,
            genericSettingsBtn
        ]
    }()
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 用户注销成功通知
        NotificationCenter.default.addObserver(forName: UserLogedout, object: nil, queue: OperationQueue.main) { [weak self] _ in
            self?.showLoginViewControllerIfNeeded(true)
        }
        
        // 导航栏
        gk_navBackgroundColor = UIColor.clear
        gk_navLeftBarButtonItem = UIBarButtonItem(imageName: "ic_nav_back", target: self, action: #selector(_backButtonTapped))
        
        // 视图
        view.insertSubview(backgroundView, at: 0)
        view.addSubviews([
            titleLabel,
            subtitleLabel,
            homepageBookIV
        ])
        view.addSubviews(gridButtons)
        _setupContraints()
        
        // 处理用户待支付订单
        _processPendingOrders()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return UIStatusBarStyle.lightContent
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - Private Methods

extension HomeViewController {
    
    // 设置视图约束
    func _setupContraints() {
        constrain(backgroundView, view) { v, parent in
            v.edges == parent.edges
        }
        
        // titleLabel
        constrain(titleLabel, gk_navigationBar, view) { v, sibling, parent in
            v.top == sibling.bottom + 10
            v.left == parent.left + 50
            v.right == parent.right - 50
            v.height == 25
        }
        
        // subtitleLabel
        constrain(subtitleLabel, titleLabel, view) { v, sibling, parent in
            v.top == sibling.bottom + 10
            v.left == sibling.left
            v.right == sibling.right
            v.height == 17
        }
        
        // gridButtons
        let kGridButtonSize = CGSize(width: 130, height: 165)
        var relatedView: UIView = subtitleLabel
        for (idx, btn) in gridButtons.enumerated() {
            let topMargin: CGFloat = idx / 2 > 0 ? 17:30
            constrain(btn, relatedView) { v, sibling in
                v.top == sibling.bottom + topMargin
                if idx % 2 == 0 {
                    v.left == sibling.left
                } else {
                    v.left == sibling.left + kGridButtonSize.width + 19
                }
                v.width == kGridButtonSize.width
                v.height == kGridButtonSize.height
            }
            if idx/2 != (idx+1)/2 {
                relatedView = gridButtons[idx-1]
            }
        }
        
        // homepageBookIV
        constrain(homepageBookIV, gridButtons.last!, view) { v, sibling, parent in
            v.top <= sibling.bottom + 30 ~ .defaultLow
            v.right == parent.right
            v.bottom == parent.bottom
            v.width == 239
        }
    }
    
    // 返回按钮点击事件
    @objc func _backButtonTapped() {
        if presentingViewController != nil {
            dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
    
    // 查看学习
    @objc func _viewStudy() {
        let vc = StudyViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    // 数据分析
    @objc func _showDataAnalysis() {
        let vc = DataAnalysisViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    // 学习设置
    @objc func _showStudySettings() {
        let vc = StudySettingsViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    // 通用设置
    @objc func _showGenericSettings() {
        let vc = GenericSettingsViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    // 处理待支付订单
    private func _processPendingOrders() {
        NetworkClient.instance.userOrders(success: { (data) in
            guard let data_ = data else {
                return
            }
            do {
                let decoder: JSONDecoder = JSONDecoder()
                let order: UserPendingOrder = try decoder.decode(UserPendingOrder.self, from: data_)
                DispatchQueue.main.async { [weak self] in
                    let vc = PurchaseViewController(order)
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            } catch {
                dbgPrint("ERROR: query user's pending orders failed with unexpected server response")
            }
        }) { (error) in
            dbgPrint("ERROR: query user's pending orders failed: \(error?.localizedDescription ?? "UNKNOWN")")
        }
    }
    
}
